//
//  XYXWaterFallLayout.swift
//  瀑布流布局
//
//  Created by monica on 2018/1/9.
//  Copyright © 2018年 xyx. All rights reserved.
//

import UIKit

//设计数据源方法
protocol XYXWaterFallLayoutDataSource:class {
    func numberOfCols(_ waterfallLayout:XYXWaterFallLayout) -> Int
    func waterfall(_ waterfall:XYXWaterFallLayout, item:Int) -> CGFloat
}

class XYXWaterFallLayout: UICollectionViewFlowLayout {

    weak var dataSource : XYXWaterFallLayoutDataSource?
    fileprivate lazy var cellAttrs: [UICollectionViewLayoutAttributes] = [UICollectionViewLayoutAttributes]()
    fileprivate lazy var cols: Int = {
        return self.dataSource?.numberOfCols(self) ?? 2
    }()

    //定义初始时，所有cell的位置
    fileprivate lazy var totalHeights: [CGFloat] = Array(repeatElement(self.sectionInset.top, count: self.cols))
}

//MARK:准备布局
extension XYXWaterFallLayout{
    override func prepare() {
        super.prepare()
        
        //获取cell个数
        let itemCount: Int = (collectionView?.numberOfItems(inSection: 0))!

        let cellW_B: CGFloat = CGFloat(cols-1) * minimumInteritemSpacing
        let cellW : CGFloat = (collectionView!.bounds.width - sectionInset.left - sectionInset.right - cellW_B)/CGFloat(cols)
        
        //给每个cell创建一个UICollectionViewLayoutAttributes
        for i in 0 ..< itemCount {
            let indexPath = IndexPath(item: i, section: 0)
            let attr = UICollectionViewLayoutAttributes(forCellWith: indexPath)
            guard let cellH : CGFloat = dataSource?.waterfall(self, item: i) else{
                fatalError("请实现对应的数据源方法，并且返回cell高度")
            }
            
            let minheight = totalHeights.min()
            let minIndex = totalHeights.index(of: minheight!)

            let cellX : CGFloat = sectionInset.left + (minimumInteritemSpacing + cellW) * CGFloat(minIndex!)
            let cellY : CGFloat = minheight! + minimumLineSpacing
            attr.frame = CGRect(x: cellX, y: cellY, width: cellW, height: cellH)

            cellAttrs.append(attr)

            //添加当前的高度
            totalHeights[minIndex!] = minheight! + minimumLineSpacing + cellH
        }
        
    }
}

//MARK:返回准备好所有布局
extension XYXWaterFallLayout{
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        return cellAttrs
    }
}

//MARK:设置contentSize
extension XYXWaterFallLayout{
    override var collectionViewContentSize: CGSize{
        return CGSize(width: 0, height: totalHeights.max()! + sectionInset.bottom)
    }
}


